package com.xianjindai.facade.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 关于银行的工具类
 * @author LiXueJian
 *
 */
public class BankUtils {
	
	private BankUtils() {
	}
	/**
	 * 验证银行卡号是否符合规范
	 * @param bankNum
	 * @return
	 */
	public static boolean checkBankNum(String bankNum){
		
		//判断银行卡号为16-19位全数字
		String regex = "^((10|18|30|35|37|40|41|42|43|44|45|46|47|48|49|50|51|52|53|54|55|56|58|60|62|65|68|69|84|87|88|94|95|98|99)\\d{14,17})$";
		Pattern pt = Pattern.compile(regex);
		Matcher mc = pt.matcher(bankNum);
		if(!mc.matches()){
			return false;
		}
		//取出最后一位
		String lastNum=bankNum.substring(bankNum.length()-1,bankNum.length());
		//前15或18位
		String first15Num=bankNum.substring(0,bankNum.length()-1);
		List<Double> newArr = new ArrayList<Double>();
		//前15或18位倒序存进数组
		for(int i=0;i<first15Num.length();i++){ 
			int reg = first15Num.length()-i;
			int reg1 = Integer.parseInt(first15Num.substring(reg-1, reg));
			Double reg2 = (double) reg1;
			newArr.add(i, reg2);
			}
		//奇数位*2的积 <9
		List<Double> arrJiShu=new ArrayList<Double>(); 
		//奇数位*2的积 >9
		List<Double> arrJiShu2=new ArrayList<Double>(); 
		//偶数位数组
		List<Double> arrOuShu=new ArrayList<Double>();   
		for(int j=0;j<newArr.size();j++){
			if((j+1)%2==1){
				//奇数位
				if(newArr.get(j)*2<9){
					arrJiShu.add(newArr.get(j)*2);
					}else{
						arrJiShu2.add(newArr.get(j)*2);
					}
			}else{
				//偶数位
				arrOuShu.add(newArr.get(j));
			}
		}
		//奇数位*2 >9 的分割之后的数组个位数
		List<Double> jishuChild1=new ArrayList<Double>();
		//奇数位*2 >9 的分割之后的数组十位数
		List<Double> jishuChild2=new ArrayList<Double>();
		for(int h=0;h<arrJiShu2.size();h++){
			Double reg4 = arrJiShu2.get(h);
			jishuChild1.add(h, reg4%10);
			jishuChild2.add(h, reg4/10);
		}        
		//奇数位*2 < 9 的数组之和
		Double sumJiShu=0.0; 
		//偶数位数组之和
		Double sumOuShu=0.0; 
		//奇数位*2 >9 的分割之后的数组个位数之和
		Double sumJiShuChild1=0.0; 
		//奇数位*2 >9 的分割之后的数组十位数之和
		Double sumJiShuChild2=0.0; 
		Double sumTotal=0.0;
		for(int m=0;m<arrJiShu.size();m++){
			sumJiShu=sumJiShu+arrJiShu.get(m);
		}
	  
		for(int n=0;n<arrOuShu.size();n++){
			sumOuShu=sumOuShu+arrOuShu.get(n);
		}
	  
		for(int p=0;p<jishuChild1.size();p++){
			sumJiShuChild1=sumJiShuChild1+jishuChild1.get(p);
			sumJiShuChild2=sumJiShuChild2+jishuChild2.get(p).intValue();
		}      
		//计算总和
		sumTotal=sumJiShu+sumOuShu+sumJiShuChild1+sumJiShuChild2;
	  
		//计算Luhm值
		Double k= sumTotal%10==0?10:sumTotal%10;        
		Double luhm= 10-k;
		int reg5 = Integer.parseInt(lastNum);
		if(reg5==luhm){
			return true;
		}else{
			return false;
		}        
	}
}
